package com.enjoy.concurrent.ch4;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "enjoy")
public class LockCase {

    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        newThread(lock, log);
        Thread thread = Thread.currentThread();
        log.info("执行完了{}", thread);
    }

    public static void newThread(Lock lock, Logger log) {
        new Thread(() -> {
            try {
                lock.lock();
                log.info("---线程开始执行了,获取锁---");
                TimeUnit.HOURS.sleep(100);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }

        new Thread(() -> {
            try {
                lock.lock();
                log.info("---线程开始执行了,获取锁---");
            } finally {
                lock.unlock();
            }
        }, "t2").start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }

        new Thread(() -> {
            try {
                lock.lock();
                log.info("---线程开始执行了,获取锁---");
            } finally {
                lock.unlock();
            }
        }, "t3").start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }
    }
}
